﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;

namespace School.SystemManage.WebPages.ArticlePage
{
    public partial class ArticleEdit : BasePage
    {
        protected string menu = string.Empty;
        protected string subMenu = string.Empty;
        protected string actionName = string.Empty;
        TechnologySchoolEntities db = new TechnologySchoolEntities();
        Article article = null;
        byte category = 0;
        bool isAdd = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            category = byte.Parse(Request.QueryString["category"]);
            SubMenu submenu = db.SubMenu.First(m => m.Categories == category);
            menu = db.SubMenu.First(m => m.Categories == submenu.ParentCategory).Name;
            subMenu = submenu.Name; 
            
            isAdd = Request.QueryString["action"] == "add";
            
            if (isAdd)
            {
                actionName = "内容添加";

                article = new Article();
            }
            else
            {
                actionName = "内容编辑";

                long articleId = long.Parse(Request.QueryString["aid"]);
                article = db.Article.FirstOrDefault(a => a.ArticleID == articleId);

                if (!Page.IsPostBack)
                {
                    BindData(article);
                }
            }

            //编辑类别不是学院新闻，则首页图片不能设定
            if (category == 23)
            {
                rbtnIsMainNews.Enabled = true;
                FileUpload1.Enabled = true;
            }
            else if (category == 24)
            {
                rbtnIsMainNews.Enabled = true;
            }
        }

        private void BindData(Article article)
        {           
            if (article != null)
            {
                txbTitle.Text = article.Title;
                editor.Value = article.Content;
                rbtnIsMainNews.SelectedIndex = ((bool)article.IsMainNews) == true ? 0 : 1;
                rbtIsEnabled.SelectedIndex = ((bool)article.IsEnabled) == true ? 0 : 1;
                if ((bool)article.IsMainNews)
                {
                    string htmlPreview = string.Format("[<a href='{0}' target='_blank'>{1}</a>]", article.ImagePath, "预览");
                    ltrMainImg.Text = htmlPreview;
                }

                var attachment = db.Attachment.Where(a => a.Article.ArticleID == article.ArticleID);
                if (attachment.Count() > 0)
                {
                    rep_Attachment.DataSource = attachment;
                    rep_Attachment.DataBind();
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (isAdd)
                {
                    bool isMainNews = (rbtnIsMainNews.SelectedValue == "1");
                    string imagePath = string.Empty;
                    if (isMainNews && FileUpload1.HasFile)
                    {
                        if (!UploadMainNewsImage(out imagePath))
                        {
                            lblMsg.Text = "上传新闻首页显示图片失败，导致添加新闻失败！";
                            return;
                        }
                    }

                    int addArticleUserID = int.Parse(GetCookie("UserLoginID"));
                    article.SubMenu = db.SubMenu.First(m => m.Categories == category);
                    article.Title = txbTitle.Text.Trim();
                    article.Content = editor.Value;
                    article.IsMainNews = isMainNews;
                    article.ImagePath = imagePath;
                    article.UpdateTime = DateTime.Now;
                    article.AdminUsers = db.AdminUsers.First(u => u.UserID == addArticleUserID);
                    article.ReadTimes = 0;
                    article.IsChecked = 0;
                    article.Remarks = string.Empty;
                    article.CheckedTime = DateTime.Now;
                    article.CheckedUserID = 0;
                    article.IsEnabled = rbtIsEnabled.SelectedValue == "1";

                    db.AddToArticle(article);
                    db.SaveChanges();

                    if (Request.Files.AllKeys.Where(k => k.ToString() == "FileUpload2").Count() != 0)
                    {
                        if (!UploadAttachment(article.ArticleID, txbFileNames.Text.Replace('，', ',').Split(',')))
                        {
                            lblMsg.Text = "添加文章内容已成功，但添加附件失败！";
                            return;
                        }
                    }

                    lblMsg.Text = "添加成功！";
                }
                else
                {
                    bool isMainNews = (rbtnIsMainNews.SelectedValue == "1");
                    string imagePath = string.Empty;
                    if (isMainNews)
                    {
                        if (FileUpload1.HasFile)
                        {
                            if (!UploadMainNewsImage(out imagePath))
                            {
                                lblMsg.Text = "上传新闻首页显示图片失败，导致更新新闻失败！";
                                return;
                            }
                        }
                        else
                        {
                            imagePath = article.ImagePath;
                        }
                    }

                    int addArticleUserID = int.Parse(GetCookie("UserLoginID"));
                    article.Title = txbTitle.Text.Trim();
                    article.Content = editor.Value;
                    article.IsMainNews = isMainNews;
                    article.ImagePath = imagePath;
                    article.UpdateTime = DateTime.Now;
                    article.AdminUsers = db.AdminUsers.First(u => u.UserID == addArticleUserID);
                    article.IsChecked = 0;
                    article.CheckedUserID = 0;
                    article.IsEnabled = rbtIsEnabled.SelectedValue == "1";

                    db.SaveChanges();

                    if (Request.Files.AllKeys.Where(k => k.ToString() == "FileUpload2").Count() != 0)
                    {
                        if (!UploadAttachment(article.ArticleID, txbFileNames.Text.Replace('，', ',').Split(',')))
                        {
                            lblMsg.Text = "修改文章内容已成功，但添加附件失败！";
                            return;
                        }
                    }

                    BindData(article);
                    lblMsg.Text = "修改成功！";
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "发生异常，原因：" + ex.Message;
            }
        }

        /// <summary>
        /// 上传首页图片
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        private bool UploadMainNewsImage(out string imagePath)
        {
            imagePath = string.Empty;
            try
            {
                //HttpPostedFile hpf = Request.Files[Request.Files.AllKeys.Single(k => k.ToString() == "FileUpload1")];
                string key = Request.Files.AllKeys.SingleOrDefault(k => k.ToString() == "FileUpload1");
                if (key == null)
                {
                    throw new ArgumentNullException("httpPostFile", "没有设置可上传的首页图片文件");
                }

                if (FileUpload1.FileContent.Length > 0)
                {
                    string originalFileName = FileUpload1.FileName;
                    string extendName = originalFileName.Substring(originalFileName.LastIndexOf('.') + 1);
                    string newFileName = Guid.NewGuid().ToString() + "." + extendName;
                    string serverSavePath = Server.MapPath(@"~\UploadFiles\NewsImages");
                    imagePath = System.IO.Path.Combine(@"\UploadFiles\NewsImages", newFileName);
                    FileUpload1.SaveAs(System.IO.Path.Combine(serverSavePath, newFileName));

                    return true;
                }
                return false;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="articleID"></param>
        /// <param name="fileNames"></param>
        /// <returns></returns>
        private bool UploadAttachment(long articleID, string[] fileNames)
        {
            try
            {
                if (Request.Files.AllKeys.Where(k => k.ToString() == "FileUpload2").Count() != fileNames.Length)
                {
                    throw new ArgumentOutOfRangeException("fileNumbers", "上传的附件数与设定的标题数不一致");
                }

                HttpFileCollection hfc = Request.Files;
                for (int i = 0, j = 0; i < hfc.Count; i++)
                {
                    if (hfc.AllKeys[i] == "FileUpload2")
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            string originalFileName = System.IO.Path.GetFileName(hpf.FileName);
                            string extendName = originalFileName.Substring(originalFileName.LastIndexOf('.') + 1);
                            string newFileName = Guid.NewGuid().ToString() + "." + extendName;
                            string serverSavePath = Server.MapPath(@"~\UploadFiles\AttachmentFiles");
                            string filePath = System.IO.Path.Combine(@"\UploadFiles\AttachmentFiles", newFileName);
                            hpf.SaveAs(System.IO.Path.Combine(serverSavePath, newFileName));

                            Attachment file = new Attachment();
                            file.Article = db.Article.First(a => a.ArticleID == articleID);
                            file.Title = fileNames[j];
                            file.FilePath = filePath;

                            db.AddToAttachment(file);

                            j++;
                        }
                    }
                }

                db.SaveChanges();
                return true;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnDel_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in rep_Attachment.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("cbChecked");
                if (cb.Checked)
                { 
                    long aid=long.Parse(((HiddenField)item.FindControl("hfAID")).Value);
                    var att = db.Attachment.First(a => a.AID == aid);
                    string filePath = Server.MapPath(att.FilePath);

                    db.DeleteObject(att);

                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }
            }

            db.SaveChanges();

            BindData(article);
        }
    }
}
